package com.amap.placesearch;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import android.support.v7.widget.SearchView;

import com.amap.api.services.help.Inputtips;
import com.amap.api.services.help.InputtipsQuery;
import com.amap.api.services.help.Tip;
import com.amap.placesearch.adapter.InputTipsAdapter;
import com.amap.placesearch.util.Constants;
import com.amap.placesearch.util.ToastUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * Tips搜索的界面
 */
public class TipsSearchActivity extends Activity implements View.OnClickListener {

    private static final String TAG = TipsSearchActivity.class.getSimpleName();

    private Context mContext;//上下文
    private SearchView mSearchView;// 输入搜索关键字
    private ImageView mBack;//返回按键
    private ListView mInputListView;//存放搜索数据的ListView
    private List<Tip> mCurrentTipList;
    private InputTipsAdapter mIntipAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_input_tips);

        initParamsAndValues();

        initView();
    }

    private void initParamsAndValues() {
        mContext = this;
    }

    private void initView() {
        mBack = findViewById(R.id.back);
        mBack.setOnClickListener(this);

        mInputListView = findViewById(R.id.inputtip_list);
        mInputListView.setOnItemClickListener(mOnItemClickListener);

        initSearchView();
    }

    private void initSearchView() {
        mSearchView = findViewById(R.id.keyWord);
        mSearchView.setOnQueryTextListener(mOnQueryTextListener);//设置输入文字的监听
        mSearchView.setIconified(false);//设置searchView处于展开状态
        mSearchView.onActionViewExpanded();//当展开无输入内容的时候，没有关闭的图标
        mSearchView.setIconifiedByDefault(true);//搜索框，默认为true在框内，false为框外。
        mSearchView.setSubmitButtonEnabled(false);//提交按钮是否显示
    }

    /**
     * ListView被点击每一个条目的时候执行的方法
     */
    OnItemClickListener mOnItemClickListener = new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            if (mCurrentTipList != null) {
                //1、获取到点击的数据。
                Tip tip = (Tip) parent.getItemAtPosition(position);
                //2、返回给页面
                Intent intent = new Intent();
                intent.putExtra(Constants.EXTRA_TIP, tip);
                setResult(MainActivity.RESULT_CODE_INPUTTIPS, intent);
                finish();
            }
        }
    };

    /**
     * 查询文字的监听
     */
    SearchView.OnQueryTextListener mOnQueryTextListener = new SearchView.OnQueryTextListener() {
        /**
         * 点击提交按钮的时候执行的方法
         * @param query
         * @return
         */
        @Override
        public boolean onQueryTextSubmit(String query) {
            Intent intent = new Intent();
            intent.putExtra(Constants.KEY_WORDS_NAME, query);
            setResult(MainActivity.RESULT_CODE_KEYWORDS, intent);
            finish();return false;
        }

        @Override
        public boolean onQueryTextChange(String newText) {
            Log.e(TAG,"onQueryTextChange:" + newText);
            if (!IsEmptyOrNullString(newText)) {
                //1、搜索的参数的类，参数1：关键字，参数2：查询的城市编码 citycode、城市名称（中文或中文全拼）、行政区划代码adcode。
                InputtipsQuery inputquery = new InputtipsQuery(newText, Constants.DEFAULT_CITY);
                inputquery.setCityLimit(true);//限制在当前城市
                //2、搜索的类。
                //输入提示类，参数1：当前Activity。参数2：查询条件
                Inputtips inputTips = new Inputtips(TipsSearchActivity.this.getApplicationContext(), inputquery);
                //3、设置搜索结果的监听
                inputTips.setInputtipsListener(mInputtipsListener);
                //4、开始异步查询
                inputTips.requestInputtipsAsyn();
            } else {
                if (mIntipAdapter != null && mCurrentTipList != null) {
                    mCurrentTipList.clear();
                    mIntipAdapter.notifyDataSetChanged();
                }
            }
            return false;
        }
    };

    /**
     * 输入提示回调
     */
    Inputtips.InputtipsListener mInputtipsListener = new Inputtips.InputtipsListener() {
        @Override
        public void onGetInputtips(List<Tip> tipList, int rCode) {
            Log.e(TAG,"rCode:"+rCode);
            if (rCode == 1000) {// 正确返回
                //1、获取到数据
                mCurrentTipList = tipList;
                List<String> listString = new ArrayList<String>();
                for (int i = 0; i < tipList.size(); i++) {
                    listString.add(tipList.get(i).getName());
                    Log.e(TAG,tipList.get(i).getName());
                }
                //2、给ListView设置数据
                mIntipAdapter = new InputTipsAdapter(getApplicationContext(), mCurrentTipList);
                mInputListView.setAdapter(mIntipAdapter);
                mIntipAdapter.notifyDataSetChanged();
            } else {
                ToastUtil.showerror(mContext, rCode);
            }
        }
    };

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.back) {//返回
            this.finish();
        }
    }

    public static boolean IsEmptyOrNullString(String s) {
        return (s == null) || (s.trim().length() == 0);
    }
}
